import ConfigParser, re, logging
from devio import Switches, Relays
from scene import Scene, Transition
from device import Sensor, HobbyBoardsHub, Switch, Relay, Device

logger = logging.getLogger(__name__)

class Config:
    def __init__(self, filename):
        self.hubs = {}
        self.switches = {}
        self.relays = {}
        self.devices = {}
        self.aliases = {}   #alias to address
        self.addresses = {} #address to alias
        self.scenes = {}
        self.parser = ConfigParser.ConfigParser()
        #parse file
        self.parse(filename)

    def stripTail(self, s):
        return re.split("\s*#", s)[0]

    def parse(self, filename):
        self.parser.read(filename)

        #read aliases
        for alias, address in self.parser.items("aliases"):
            addr = self.stripTail(address)
            self.aliases[alias] = addr
            self.addresses[addr] = alias

        #NEW
        #hubs
        for alias, address in self.parser.items("aliases"):
            if HobbyBoardsHub.isFamily(address):
                hub = HobbyBoardsHub(address, alias, self)
                hub.init()
                self.hubs[address] = hub
                logger.debug(hub)
        
        #switches
        for alias, address in self.parser.items("aliases"):
            if Sensor.isFamily(address, Switch._family):
                for sw, swname in Switches.names.iteritems():
                    section = alias + "." + swname
                    if section in self.parser.sections():
                        s = Switch(address, alias, swname, self)
                        s.init()
                        self.switches[section] = s
                        logger.debug(s)
                        logger.debug(s.redir)
        #end NEW        


        #scenes
        for section in self.parser.sections():
            if re.match("^scene.+", section):
                logger.debug("scene: " + section)
                scene = Scene(section)
                for key, value in self.parser.items(section):
                    t = Transition()
                    r = re.split("\.", key)
                    t.addr = self.aliases[r[0]]
                    t.relay = eval("Relays." + r[1].capitalize())
                    r = re.split("[\:\s#]", value)
                    t.state = int(r[0])
                    try:
                        v = float(r[1])
                    except ValueError:
                        v = 0
                    t.delay = v 
                    scene.transitions.append(t)
                    logger.debug("%s, %s, %d, %f" % (t.addr, t.relay, t.state, t.delay))
                self.scenes[section] = scene
            


    def parseScenes(self):
        pass

